package com.stool.cloud.api;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.stool.cloud.config.SentinelFlowLimitHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author Felix YF Dong
 * @Description
 * @Date 2023/2/6
 */
@Slf4j
@RestController
public class FlowLimitApi {

    @GetMapping("/testA")
    public String testA()
    {
        return "------testA";
    }

    @GetMapping("/testB")
    public String testB()
    {
        try {
            TimeUnit.MILLISECONDS.sleep(800);
        } catch (InterruptedException e) {e.printStackTrace(); }
        return "------testB";
    }

    @GetMapping("/testC")
    public String testC()
    {
        log.info(Thread.currentThread().getName()+"\t"+"...testC");
        return "------testC";
    }

    @GetMapping("/testD")
    public String testD()
    {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {e.printStackTrace(); }
        log.info("testD 测试RT");
        return "------testD";
    }

    @GetMapping("/hot-key")
    @SentinelResource(value = "hot-key", blockHandler = "dealHotKey")
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,
                              @RequestParam(value = "p2", required = false) String p2) {
        return p1 + "*" + p2 + "------hot-key";
    }

    public String dealHotKey(String p1, String p2, BlockException exception) {
        return p1 + "*" + p2 + "**dealHotKey";
    }

    @GetMapping("/hot-key1")
    @SentinelResource(value = "hot-key1"
            , blockHandlerClass = SentinelFlowLimitHandler.class
            , blockHandler = "handlerException2")
    public String testHotKey1() {
        return "------hot-key1";
    }
}
